// stores/categoryStore.ts
import { defineStore } from 'pinia';
import type { chatData, chatLast } from '@/types/type';
import { reqChatlast, reqChatRecords } from '@/api/chat';
import { formatDate } from '@/utils/time';


// 定义并导出 CategoryStore
const useUserChatStore = defineStore('UserChat', {
  // 定义 state，存储分类相关的数据（原本是聊天记录）
  state: () => ({
    newsData: [] as chatLast[], // 存储消息数据，您可以根据实际需要修改类型
    chat_records: [] as chatData[]
  }),

  // 定义 actions，处理具体的数据操作
  actions: {
    // 获取与各个好友的最后一条聊天记录
    async friendsChat(userId: string, roomNames: string[] | string) {
      const result = await reqChatlast({ userId, roomNames });
      if (result.code == 200) {
        this.newsData.splice(0, this.newsData.length, ...result.data.map((item: any) => {
          if (item.timestamp) {
            item.timestamp = formatDate(item.timestamp);
          }
          return item;
        }))
        if (localStorage.getItem('selectedFriendId')) {
          this.updateSelection(localStorage.getItem('selectedFriendId'))
        }
      }
    },
    // 更新单个好友的最后一条消息


    async updatefriendChat(userId: string, roomNames: string) {
      const result = await reqChatlast({ userId, roomNames });
      if (result.code == 200) {
        // 如果获取到的数据存在且有有效数据
        if (result.data && result.data.length > 0) {
          const updatedItem = result.data[0]; // 获取更新后的最新聊天数据

          // 查找 `newsData` 中是否有匹配的好友项
          const index = this.newsData.findIndex((item: any) => item._id === updatedItem._id);

          // 如果找到了该项，则更新它
          if (index !== -1) {
            // 更新该项的最后一条消息信息
            this.newsData[index] = { ...this.newsData[index], ...updatedItem };

            // 格式化时间戳
            if (this.newsData[index].timestamp) {
              this.newsData[index].timestamp = formatDate(this.newsData[index].timestamp);
            }
          }
        }

        // 如果有选中的好友ID，更新选择的好友
        if (localStorage.getItem('selectedFriendId')) {
          this.updateSelection(localStorage.getItem('selectedFriendId'));
        }
      }
    },
    updateSelection(friendId: any) {
      this.newsData.forEach(item => {
        if (item.senderId === friendId || item.receiverId === friendId) {
          item.selected = true;
        } else {
          item.selected = false;
        }
      });
    },
    updateunreadCount(fid: string, count: number) {
      // 遍历把newsData，把unreadCount修改为count
      this.newsData.forEach(item => {
        if (item.senderId === fid || item.receiverId === fid) {
          item.unreadCount = count;
          console.log(item.unreadCount);

        }
      });



    },
    //  获取聊天记录
    async getChatRecords(userId:string, roomName: string, keyword?: string) {
      const result = await reqChatRecords({userId, roomName, keyword })
      if (result.code == 200) {
        // 格式化每条信息的时间戳
        this.chat_records.splice(0, this.chat_records.length, ...result.data.map((item: any) => {
          // 假设每条消息有一个 timestamp 字段
          if (item.timestamp) {
            item.timestamp = formatDate(item.timestamp);  // 将时间戳格式化
          }
          return item;
        }));
      }
    },

  },


  // 定义 getters，派生数据（可以根据需求扩展）
  getters: {

  },
});

export default useUserChatStore;
